<script setup lang="ts">
import { loginByQQ } from '@/services/user'
import { onMounted, onUnmounted, ref } from 'vue'
import { mobileRules, codeRules } from '@/utils/rules'
import { Toast, type FormInstance } from 'vant'
import { setMobileCode, bindMobile } from '@/services/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import type { User } from '@/types/user'
const openId = ref('')
const isBind = ref(false)

// 获取openId
onMounted(() => {
  // 先判断是否qq登录成功了
  if (window.QC.Login.check()) {
    // 再获取qq的openId
    window.QC.Login.getMe((id) => {
      console.log('openId', id)
      openId.value = id
      // 利用qq的openId 登录
      // const res = await loginByQQ()
      // promise的写法
      loginByQQ(id)
        .then((res) => {
          // 登录成功了 直接跳转走
          console.log('登录成功了', id)
          loginSuccess(res)
        })
        .catch(() => {
          // 登录失败
          isBind.value = true
        })
    })
  }
})
// 登录成功
const store = useUserStore()
const router = useRouter()
const loginSuccess = (res: { data: User }) => {
  store.setUser(res.data)
  router.replace(store.returnUrl || '/user')
  Toast.success('登录成功')
  store.setReturnUrl('')
}

// 表单登录
const mobile = ref('')
const code = ref('')
const bind = async () => {
  const res = await bindMobile({
    mobile: mobile.value,
    code: code.value,
    openId: openId.value
  })
  loginSuccess(res)
}

// 发送验证码
const form = ref<FormInstance>()
const time = ref(0)
let timeId: number
const send = async () => {
  if (time.value > 0) return
  // 验证手机号是否合格
  await form.value?.validate('mobile')
  await setMobileCode(mobile.value, 'bindMobile')
  Toast.success('发送成功')
  time.value = 60
  // 倒计时
  clearInterval(timeId)
  timeId = window.setInterval(() => {
    time.value--
    if (time.value <= 0) window.clearInterval(timeId)
  }, 1000)
}

onUnmounted(() => {
  window.clearInterval(timeId)
})
</script>

<template>
  <div class="login-page" v-if="isBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="form" @submit="bind">
      <van-field
        v-model="mobile"
        :rules="mobileRules"
        name="mobile"
        placeholder="请输入手机号"
      ></van-field>
      <van-field :rules="codeRules" v-model="code" name="code" placeholder="请输入验证码">
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">{{
            time > 0 ? `${time}s后再次发送` : '发送验证码'
          }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit"> 立即绑定 </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
